﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;

using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Extensions;
using SIG.ViewModel.Admin.Links;
using SIG.InputModel.Admin.Links;
using SIG.ViewModel;
using System;
using SIG.Infrastructure.Helper;
using System.Xml.Linq;
using SIG.Resources.Admin;
using SIG.DAL.Dapper.Repositories;
using SIG.DAL.Dapper.Model;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]   
    public class LinkController : BaseController
    {
        private readonly LinkCategoryRepository _categoryService;
        private readonly LinkRepository _linkService;
        private readonly PageMetaRepository _pageMetaService;
        private readonly IMapper _mapper;

        public LinkController(IMapper mapper)
        {
            _categoryService = new LinkCategoryRepository();
            _linkService = new LinkRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;


        }
        #region Links
        

    [HttpGet]
        public ActionResult Index(int? page, int? categoryId, string Keyword)
        {

            var linkListVM = new LinkListVM();

            linkListVM.CategoryId = categoryId ?? 0;
            linkListVM.PageIndex = (page ?? 1);
            linkListVM.PageSize = SettingsManager.Link.PageSize;
            linkListVM.Keyword = Keyword;

            int count;
            var links = _linkService.GetListPagedItems(linkListVM.PageIndex, linkListVM.PageSize, (int)linkListVM.CategoryId, linkListVM.Keyword, out count);

            foreach(var item in links)
            {
                item.LinkCategory = _categoryService.GetById(item.CategoryId);
            }
            linkListVM.TotalCount = count;

            var categoryList = _categoryService.GetActiveItems().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(categoryList, "Id", "Title");
            ViewBag.Categories = categories;

            linkListVM.Links = new StaticPagedList<Link>(links, linkListVM.PageIndex , linkListVM.PageSize, linkListVM.TotalCount);
            // ViewBag.OnePageOfLinks = linksAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(linkListVM);

        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/LinkSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }




        public ActionResult Add()
        {
            var link = new LinkIM { Active = true };

            var categorys = _categoryService.GetActiveItems().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;
            return View(link);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(LinkIM link)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var newLink = _mapper.Map<LinkIM, Link>(link);
                newLink.CreatedBy = Site.CurrentUserName;
                newLink.CreatedDate = DateTime.Now;
                _linkService.Create(newLink);

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Link));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vLink = _linkService.GetById(Id);
            if (vLink == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var editLink = _mapper.Map<Link, LinkIM>(vLink);

            var categorys = _categoryService.GetActiveItems().OrderByDescending(m => m.Importance).ToList();
            var lCategorys = new SelectList(categorys, "Id", "Title");

            ViewBag.Categories = lCategorys;

            return View(editLink);


        }

        [HttpPost]       
        [ValidateAntiForgeryToken]
        public JsonResult Edit(LinkIM link)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                var editLink = _linkService.GetById(link.Id);
                editLink.Title = link.Title;
                editLink.Importance = link.Importance;
                editLink.LogoUrl = link.LogoUrl;
                editLink.Active = link.Active;
                editLink.CategoryId = link.CategoryId;
                editLink.Description = link.Description;
                editLink.WebLink = link.WebLink;
                editLink.UpdatedBy = Site.CurrentUserName;
                editLink.UpdatedDate = DateTime.Now;
               // var editLink = _mapper.Map<LinkIM, Link>(link);
                _linkService.Update(editLink);                      

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Link));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Link vLink = _linkService.GetById(id);

            try
            {
                vLink.Active = !vLink.Active;
                _linkService.Update(vLink);
                vLink.LinkCategory = _categoryService.GetById(vLink.CategoryId);
              //  var vm = _mapper.Map<LinkVM>(vLink);

                AR.Data = RenderPartialViewToString("_LinkItem", vLink);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Link));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        //  [HttpPost]
        //  [ValidateAntiForgeryToken]
        //  public JsonResult Recommend(int id)
        //  {

        //      Link vLink = _linkService.GetById(id);

        //      try
        //      {
        //          vLink.Recommend = !vLink.Recommend;
        //          _linkService.Update(vLink);

        //          var vm = _mapper.Map<LinkVM>(vLink);
        //          AR.Data = RenderPartialViewToString("_LinkItem", vm);
        //          AR.SetSuccess(String.Format(Resources.Messages.AlertUpdateSuccess, Resources.EntityNames.Link));
        //          return Json(AR, JsonRequestBehavior.DenyGet);

        //      }
        //      catch (Exception ex)
        //      {
        //          AR.Setfailure(ex.Message);
        //          return Json(AR, JsonRequestBehavior.DenyGet);
        //      }

        //  }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Link vLink = _linkService.GetById(id);

            if (vLink == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _linkService.Delete(vLink);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Link));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        #endregion


    }
}
